package com.gm.wholesale.module.order.ui

import android.text.TextUtils
import android.util.ArrayMap
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import com.gm.commonlib.base.baseAdapter.CommonAdapter
import com.gm.commonlib.base.baseAdapter.ViewHolder
import com.gm.commonlib.base.baseBean.BasePageData
import com.gm.commonlib.base.baseui.baseListviewUI.BaseListFragment
import com.gm.commonlib.module.evenbus.EventMessage
import com.gm.commonlib.network.HttpServicesHolder
import com.gm.commonlib.util.timeUtils.DateTimeUtils
import com.gm.commonlib.views.timePickerView.TimePickerViewUtils
import com.gm.wholesale.R
import com.gm.wholesale.constant.Constant
import com.gm.wholesale.module.evenbus.EvenBusUtil
import com.gm.wholesale.module.evenbus.EventBusType
import com.gm.wholesale.module.order.api.IOrderApi
import com.gm.wholesale.module.order.bean.OrderBean
import com.gm.wholesale.module.order.bean.OrderDetailBean
import com.gm.wholesale.module.order.interfaces.ISearchOrderByTime
import com.gm.wholesale.module.order.orderStatus.OrderStatusType
import io.reactivex.Observable

open class OrderListFragment : BaseListFragment<OrderBean?, BasePageData<OrderBean?>?>(),
    ISearchOrderByTime {
    private var mOrderingTimeBegin: String? = null
    private var mOrderingTimeEnd: String? = null
    private var headerView: View? = null
    private var mOrderMangerFragment: OrderMangerFragment? = null
    fun updateView() {
        mOrderingTimeBegin = null
        refreshData()
    }
    override fun onCreateContentHeader(parent: ViewGroup) {
        super.onCreateContentHeader(parent)
        headerView = LayoutInflater.from(context).inflate(R.layout.view_order_header, parent)
        val choiceTimeTv = headerView?.findViewById<TextView>(R.id.choiceTimeTv)
        val time = DateTimeUtils.formatDateTime(System.currentTimeMillis(), DateTimeUtils.HMD2)
        choiceTimeTv?.text = "$time(今天)"
        choiceTimeTv?.setOnClickListener {
            var nowTime = System.currentTimeMillis()
            if (!TextUtils.isEmpty(mOrderingTimeBegin)) {
                nowTime = DateTimeUtils.getTimeStringToLong(
                    mOrderingTimeBegin,
                    DateTimeUtils.LONG_DATETIME_FORMAT_STRING
                )
            }
            TimePickerViewUtils.showTimeByYMD(context, "选择时间", nowTime) { date, v ->
                mOrderingTimeBegin =
                    DateTimeUtils.formatDateTime(date, DateTimeUtils.SHORT_DATETIME_FORMAT_STRING)
                mOrderingTimeEnd = "$mOrderingTimeBegin 23:59:59"
                mOrderingTimeBegin = "$mOrderingTimeBegin 00:00:00"
                var time = DateTimeUtils.formatDateTime(date, DateTimeUtils.HMD2)
                if (DateTimeUtils.isToday(date)) {
                    time = "$time(今天)"
                }
                choiceTimeTv.text = time
                refreshData()
            }
        }
        hidHeaderView()
    }

    private fun hidHeaderView() {
        headerView?.visibility = View.GONE
    }

    override fun initPullToRefreshListView() {
        super.initPullToRefreshListView()
        setBodybg(resources.getColor(R.color.white))
        pullToRefreshListView.divider = resources.getDrawable(R.drawable.list_driver_shap)
    }

    override fun getDataFinish(mDatas: MutableList<OrderBean?>?) {
        if (!mDatas.isNullOrEmpty()) {
            mDatas[0]?.isClick = true
            showOrderDetail(mDatas[0])
        } else {
            if (mOrderMangerFragment == null) return
            mOrderMangerFragment?.hasNotOrderData()
        }
    }

    override fun createTempBaseAdapter(): BaseAdapter {
        return object :
            CommonAdapter<OrderBean?>(activity, mDatas, R.layout.list_order_manger_item) {
            override fun convert(viewHolder: ViewHolder?, data: OrderBean?) {
                if (viewHolder != null && data != null) {
                    if (data.isClick) {
                        viewHolder.convertView.setBackgroundColor(mContext.resources.getColor(R.color.color_e4f4eb))
                    } else {
                        viewHolder.convertView.setBackgroundColor(mContext.resources.getColor(R.color.white))
                    }
                    val aftersaTv = viewHolder.getView<TextView>(R.id.afterOrderNt)
                    aftersaTv.visibility = View.GONE
                    if (data.isAftersale) {
                        aftersaTv.visibility = View.VISIBLE
                    }
                    viewHolder.setText(R.id.userNameTv, data.customerName)
                    viewHolder.setText(R.id.orderNumTv, data.orderNo)
                    viewHolder.setText(R.id.orderPriceTv, "￥" + data.salesAmount)
                    viewHolder.setText(R.id.createTimeTv, data.orderingTime)
                    showOrderState(data, viewHolder.getView(R.id.orderStateTv))
                    viewHolder.convertView.setOnClickListener {
                        setDataClick(data)
                        notifyDataSetChanged()
                        showOrderDetail(data)
                    }
                }

            }
        }
    }

    private fun showOrderDetail(orderBean: OrderBean?) {
        EvenBusUtil.updateOrderDetail(orderBean)
    }

    private fun setDataClick(clickData: OrderBean) {
        for (data in mDatas) {
            data?.isClick = data?.orderId == clickData.orderId
        }
    }

    private fun showOrderState(data: OrderBean, textView: TextView) {
        val payStatus = data.paidStatus
        if (payStatus == OrderStatusType.WWC.type) {
            textView.text = "未支付"
            textView.setTextColor(context.resources.getColor(R.color.color_FF4D4F))
        } else if (data.paidStatus == OrderStatusType.YYS.type) {
            textView.text = "已结清"
            textView.setTextColor(context.resources.getColor(R.color.color_06AE56))
        } else {
            textView.text = "未结清"
            textView.setTextColor(context.resources.getColor(R.color.color_FF4D4F))
        }
    }

    override fun getHttpServicesHolder(index: Long): HttpServicesHolder<*, BasePageData<OrderBean?>?>? {
        return object : HttpServicesHolder<IOrderApi?, BasePageData<OrderBean?>?>() {
            override fun getHttpObservable(instance: IOrderApi?): Observable<BasePageData<OrderBean?>?> {
                val quearyData: ArrayMap<String, Any?> = arrayMap
                quearyData["page"] = index
                quearyData["pageSize"] = Constant.DEFAULTPAGESIZE
                return instance!!.getOrderList(quearyData)
            }
        }
    }

    val arrayMap: ArrayMap<String, Any?>
        get() {
            //订单类型，1-小程序现场单，2-小程序提前单，3-批发版现场单
            val queryData = ArrayMap<String, Any?>()
            queryData["type"] = 3
            if (TextUtils.isEmpty(mOrderingTimeBegin)) {
                mOrderingTimeBegin = DateTimeUtils.formatDateTime(
                    System.currentTimeMillis(),
                    DateTimeUtils.SHORT_DATETIME_FORMAT_STRING
                )
                mOrderingTimeEnd = "$mOrderingTimeBegin 23:59:59"
                mOrderingTimeBegin = "$mOrderingTimeBegin 00:00:00"
            }
            queryData["orderingTimeStart"] = mOrderingTimeBegin
            queryData["orderingTimeEnd"] = mOrderingTimeEnd
            return queryData
        }

    override fun onReceiveEvent(event: EventMessage<*>) {
        if (event.code == EventBusType.UPDATE_ORDER_LIST.type) {
            updateListView(event.data as OrderDetailBean)
        }
    }

    private fun updateListView(orderDetailBean: OrderDetailBean) {
        val orderInfoDTO = orderDetailBean.orderInfo
        if (orderInfoDTO == null || mDatas.isEmpty()) {
            return
        }
        for (orderBean in mDatas) {
            if (orderInfoDTO.orderId == orderBean?.orderId) {
                orderBean.paidStatus = orderInfoDTO.paidStatus
                notifyListDataSetChanged()
                break
            }
        }
    }

    override fun searchOrderByTime(begTime: String, endTime: String) {
        mOrderingTimeBegin = begTime
        mOrderingTimeEnd = endTime
        refreshData()
    }
}